﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Core.Interceptor;
using System.Reflection;
using System.ComponentModel;

namespace EasyProp
{
    internal class PropertySetInterceptor : IInterceptor
    {
        public void AddBeforeFilter(IPropertySetterFilter propertySetterBeforeFilter)
        {
            _beforeFilters.Add(propertySetterBeforeFilter);
        }

        public void AddAfterFilter(IPropertySetterFilter propertySetterAfterFilter)
        {
            _afterFilters.Add(propertySetterAfterFilter);
        }

        #region IInterceptor Members

        public void Intercept(IInvocation invocation)
        {
            if (_beforeFilters.Count == 0 && _afterFilters.Count == 0 ||
               (!invocation.Method.Name.StartsWith("set_")))
            {
                invocation.Proceed();
                return;
            }

            string propertyName = invocation.Method.Name.Substring(4);
            bool keepFiltering = true;
            foreach (IPropertySetterFilter beforeFilter in _beforeFilters)
            {
                keepFiltering = beforeFilter.Execute(invocation, propertyName);
                if (!keepFiltering)
                {
                    break;
                }
            }

            if (keepFiltering)
            {
                invocation.Proceed();

                foreach (IPropertySetterFilter afterFilter in _afterFilters)
                {
                    keepFiltering = afterFilter.Execute(invocation, propertyName);
                    if (!keepFiltering)
                    {
                        break;
                    }
                }
            }
        }

        #endregion

        readonly List<IPropertySetterFilter> _beforeFilters = new List<IPropertySetterFilter>();
        readonly List<IPropertySetterFilter> _afterFilters = new List<IPropertySetterFilter>();
    }
}
